package com.example.demo.conf;

import org.apache.commons.codec.binary.Base64;
import org.springframework.security.oauth2.common.*;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.nio.charset.StandardCharsets;

/**
 * TODO
 *
 * @author funcas
 * @since 1.0
 */
public class MyTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        if (accessToken instanceof DefaultOAuth2AccessToken){
            DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
            token.setValue(Base64.encodeBase64URLSafeString(token.getValue().getBytes(StandardCharsets.UTF_8)));
            DefaultExpiringOAuth2RefreshToken refreshToken = (DefaultExpiringOAuth2RefreshToken)token.getRefreshToken();
            if (refreshToken instanceof DefaultExpiringOAuth2RefreshToken) {
                if(authentication.getOAuth2Request().getRefreshTokenRequest() == null) {
                    String newRefreshToken = Base64.encodeBase64URLSafeString(refreshToken.getValue().getBytes(StandardCharsets.UTF_8));
                    token.setRefreshToken(new DefaultExpiringOAuth2RefreshToken(newRefreshToken, refreshToken.getExpiration()));
                }
            }
            return token;
        }
        return accessToken;
    }
}
